package com.sfzlot.dev.netty.utils;


import com.sfzlot.dev.netty.bean.Message;
import com.sfzlot.dev.netty.constant.Constant;
import com.sfzlot.dev.netty.server.server.handler.ServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;

/**
 * 发送指令工具类
 * @author laimin
 *
 */
public class CommandUtils {

	final static Logger logger = LoggerFactory.getLogger(CommandUtils.class);

	/**
	 * 发送登录返回的指令，需要更改ServerHandler.connectMap的vin
	 * @param message
	 * @return
	 */
	public static String responseLogin(Message message) {
		logger.info("解析发送数据为:{}", message);
		//发送返回的报文
    	Channel ctx = ServerHandler.connectMap.get(Constant.CHANNEL + message.getVin());
    	if(ctx == null) {
    		throw new RuntimeException("该设备未登录");
    	}
		ctx.writeAndFlush(message);
		return "发送指令成功！";
    }

	/**
	 * 发送指令
	 * @param message
	 * @return
	 */
	public static String cmd(Message message) {
		logger.info("解析发送数据为:{}", message);
    	Channel ctx = ServerHandler.connectMap.get(Constant.CHANNEL + message.getVin());
    	if(ctx == null) {
    		throw new RuntimeException("该设备未登录");
    	}
		ctx.writeAndFlush(message);
		return "发送指令成功！";
    }

	/**
	 * 发送指令
	 * @param vin
	 * @return
	 */
	public static String close(String vin) {
		logger.info("断开的设备:{}", vin);
    	Channel ctx = ServerHandler.connectMap.get(Constant.CHANNEL + vin);
    	if(ctx == null) {
    		throw new RuntimeException("该设备未登录");
    	}
		ctx.close();
		return "设备已关闭！";
    }
	
}
